package com.fn.push.utils;

import com.getui.push.v2.sdk.ApiHelper;
import com.getui.push.v2.sdk.GtApiConfiguration;
import com.getui.push.v2.sdk.api.PushApi;
import com.getui.push.v2.sdk.common.ApiResult;
import com.getui.push.v2.sdk.dto.CommonEnum;
import com.getui.push.v2.sdk.dto.req.Audience;
import com.getui.push.v2.sdk.dto.req.Settings;
import com.getui.push.v2.sdk.dto.req.Strategy;
import com.getui.push.v2.sdk.dto.req.message.PushBatchDTO;
import com.getui.push.v2.sdk.dto.req.message.PushChannel;
import com.getui.push.v2.sdk.dto.req.message.PushDTO;
import com.getui.push.v2.sdk.dto.req.message.PushMessage;
import com.getui.push.v2.sdk.dto.req.message.android.AndroidDTO;
import com.getui.push.v2.sdk.dto.req.message.android.GTNotification;
import com.getui.push.v2.sdk.dto.req.message.android.ThirdNotification;
import com.getui.push.v2.sdk.dto.req.message.android.Ups;
import com.getui.push.v2.sdk.dto.res.TaskIdDTO;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Map;

public class PushUtils {

    /**
     * 应用配置
     */
    private static PushApi apiConfig() {
        GtApiConfiguration apiConfiguration = new GtApiConfiguration();
        apiConfiguration.setAppId("DEOB0OBf3LAjRDxDtgjEi7");
        apiConfiguration.setAppKey("7qPScWS7vS9u1fBjfUy4jA");
        apiConfiguration.setMasterSecret("LNUV32RYyq61tHmQCMYVg");
        // 接口调用前缀，请查看文档: 接口调用规范 -> 接口前缀, 可不填写appId
        apiConfiguration.setDomain("https://restapi.getui.com/v2/");
        // 实例化ApiHelper对象，用于创建接口对象
        ApiHelper apiHelper = ApiHelper.build(apiConfiguration);
        // 创建对象，建议复用。目前有PushApi、StatisticApi、UserApi
        return apiHelper.creatApi(PushApi.class);
    }

    /**
     * 配置推送条件
     */
    private static Settings getSettings() {
        //配置推送条件
        // 1: 表示该消息在用户在线时推送个推通道，用户离线时推送厂商通道;
        // 2: 表示该消息只通过厂商通道策略下发，不考虑用户是否在线;
        // 3: 表示该消息只通过个推通道下发，不考虑用户是否在线；
        // 4: 表示该消息优先从厂商通道下发，若消息内容在厂商通道代发失败后会从个推通道下发。
        Strategy strategy = new Strategy();
        strategy.setDef(1);
        Settings settings = new Settings();
        settings.setStrategy(strategy);
        //消息有效期，走厂商消息需要设置该值
        settings.setTtl(3600000);
        return settings;
    }

    /**
     * 推送消息体
     */
    private static void sendMessage(PushDTO<?> pushDTO, String title, String content, String payload, String intent, String url) {
        // 设置推送参数 requestid需要每次变化唯一
        pushDTO.setRequestId(System.currentTimeMillis() + "");
        pushDTO.setSettings(getSettings());
        PushChannel pushChannel = new PushChannel();
        //安卓离线厂商通道推送消息体
        AndroidDTO androidDTO = new AndroidDTO();
        Ups ups = new Ups();
        ThirdNotification thirdNotification = new ThirdNotification();
        System.out.println(title + content);
        thirdNotification.setTitle("离线标题：" + title);
        thirdNotification.setBody("离线内容：" + content);
        //ClickType:点击通知后续动作,
        //目前支持5种后续动作，
        //intent：打开应用内特定页面，
        //url：打开网页地址，
        //payload：启动应用加自定义消息内容，
        //startapp：打开应用首页，
        //none：纯通知，无后续动作
        if (StringUtils.isEmpty(payload) && StringUtils.isEmpty(intent) && StringUtils.isEmpty(url)) {
            thirdNotification.setClickType(CommonEnum.ClickTypeEnum.TYPE_STARTAPP.type);
        } else if (StringUtils.isEmpty(payload) && StringUtils.isEmpty(url)) {
            thirdNotification.setClickType(CommonEnum.ClickTypeEnum.TYPE_INTENT.type);
            thirdNotification.setIntent("intent:#Intent;launchFlags=0x04000000;action=android.intent.action.oppopush;component=io.dcloud.fire/" + intent + ";S.UP-OL-SU=true;S.title=离线测试标题;S.content=离线测试内容;S.payload=test;end");
        } else if (StringUtils.isEmpty(payload) && StringUtils.isEmpty(intent)) {
            thirdNotification.setClickType(CommonEnum.ClickTypeEnum.TYPE_URL.type);
            thirdNotification.setUrl(url);
        } else if (StringUtils.isEmpty(intent) && StringUtils.isEmpty(url)) {
            thirdNotification.setClickType(CommonEnum.ClickTypeEnum.TYPE_PAYLOAD.type);
            thirdNotification.setPayload(payload);
        }
        ups.setNotification(thirdNotification);
        //各厂商自有功能单项设置
        ups.addOption("HW", "/message/android/notification/badge/class", "io.dcloud.PandoraEntry ");
        ups.addOption("HW", "/message/android/notification/badge/add_num", 1);
        ups.addOption("HW", "/message/android/notification/importance", "HIGH");
        ups.addOption("VV", "classification", 1);
        androidDTO.setUps(ups);
        pushChannel.setAndroid(androidDTO);
        pushDTO.setPushChannel(pushChannel);

        // PushMessage在线走个推通道才会起作用的消息体
        PushMessage pushMessage = new PushMessage();
        pushDTO.setPushMessage(pushMessage);
        GTNotification notification = new GTNotification();
        notification.setTitle(title);
        notification.setBody(content);
        if (StringUtils.isEmpty(payload) && StringUtils.isEmpty(intent) && StringUtils.isEmpty(url)) {
            notification.setClickType(CommonEnum.ClickTypeEnum.TYPE_STARTAPP.type);
        } else if (StringUtils.isEmpty(payload) && StringUtils.isEmpty(url)) {
            notification.setClickType(CommonEnum.ClickTypeEnum.TYPE_INTENT.type);
            notification.setIntent("intent:#Intent;launchFlags=0x04000000;action=android.intent.action.oppopush;component=io.dcloud.fire/" + intent + ";S.UP-OL-SU=true;S.title=离线测试标题;S.content=离线测试内容;S.payload=test;end");
        } else if (StringUtils.isEmpty(payload) && StringUtils.isEmpty(intent)) {
            notification.setClickType(CommonEnum.ClickTypeEnum.TYPE_URL.type);
            notification.setUrl(url);
        } else if (StringUtils.isEmpty(intent) && StringUtils.isEmpty(url)) {
            notification.setClickType(CommonEnum.ClickTypeEnum.TYPE_PAYLOAD.type);
            notification.setPayload(payload);
        }
        pushMessage.setNotification(notification);
    }

    /**
     * 对指定用户进行单推
     */
    public static void pushToSingle(String cid, String title, String content, String payload, String intent, String url) {

        PushDTO<Audience> pushDTO = new PushDTO<>();
        sendMessage(pushDTO, title, content, payload, intent, url);
//      设置接收人信息u
        Audience audience = new Audience();
        audience.addCid(cid);
        pushDTO.setAudience(audience);
//      进行cid单推
        ApiResult<Map<String, Map<String, String>>> apiResult = apiConfig().pushToSingleByCid(pushDTO);

        if (apiResult.isSuccess()) {
            // success
            System.out.println("推送成功" + apiResult.getData());
        } else {
            // failed
            System.out.println("推送失败" + "code:" + apiResult.getCode() + ", msg: " + apiResult.getMsg());
        }
    }

    /**
     * 根据cid进行批量推送
     */
    public static void pushBatch(List<String> CIDs, String title, String content, String payload, String intent, String url) {
        PushDTO<Audience> pushDTO = new PushDTO<>();
        sendMessage(pushDTO, title, content, payload, intent, url);
//      设置接收人信息u
        Audience audience = new Audience();
        PushBatchDTO batchDTO = new PushBatchDTO();
        batchDTO.setAsync(true);
        for (String cid : CIDs) {
            audience.addCid(cid);
            pushDTO.setAudience(audience);
            batchDTO.addPushDTO(pushDTO);
        }
//        进行cid批量推
        ApiResult<Map<String, Map<String, String>>> apiResult = apiConfig().pushBatchByCid(batchDTO);

        if (apiResult.isSuccess()) {
            // success
            System.out.println("推送成功" + apiResult.getData());
        } else {
            // failed
            System.out.println("推送失败" + "code:" + apiResult.getCode() + ", msg: " + apiResult.getMsg());
        }
    }

    /**
     * 对所有app用户群推通知
     */
    public static void pushAllApp(String title, String content, String payload, String intent, String url) {

        PushDTO<String> pushDTO = new PushDTO<String>();
        sendMessage(pushDTO, title, content, payload, intent, url);
        //群推
        ApiResult<TaskIdDTO> apiResult = apiConfig().pushAll(pushDTO);

        if (apiResult.isSuccess()) {
            // success
            System.out.println("推送成功" + apiResult.getData());
        } else {
            // failed
            System.out.println("推送失败" + "code:" + apiResult.getCode() + ", msg: " + apiResult.getMsg());
        }
    }
}